<template>
  <basic-container>
    <avue-crud v-if="this.selectMer.userMerchantType !== 4" :option="option" :table-loading="loading" :data="data" :page.sync="page" ref="crud" @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @sort-change="sortChange" @on-load="onLoad">

      <template slot-scope="{row}" slot="isRefundBtn">
        <span>{{ setIsOnName(row.isRefundBtn) }}</span>
      </template>
      <template slot-scope="{row}" slot="isOn">
        <span>{{ setIsOnName(row.isOn) }}</span>
      </template>
      <template slot-scope="{ row }" slot="staffType">
        <el-tag effect="dark" v-if="row.staffType === 0" style="border:none">{{ row.staffTypeName }}</el-tag>
        <el-tag color="#E6A23C" effect="dark" v-if="row.staffType === 1" style="border:none">{{ row.staffTypeName }}</el-tag>
        <el-tag color="#67C23A" effect="dark" v-if="row.staffType === 2" style="border:none">{{ row.staffTypeName }}</el-tag>
      </template>
      
      <template slot="menuLeft">
        <el-button type="success" icon="el-icon-plus" size="small" @click.stop="handleAdd(2)" v-if="selectMer.userMerchantType === 1 || selectMer.userMerchantType === 2">商户管理员</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleAdd(1)" v-if="selectMer.userMerchantType === 1 || selectMer.userMerchantType === 2">门店管理员</el-button>
        <el-button type="warning" icon="el-icon-plus" size="small" @click.stop="handleAdd(0)">收银员</el-button>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleEdit(scope.row)">修 改</el-button>
      </template>
    </avue-crud>
    <!-- 新建 -->
    <el-dialog :title="dialogTitle" top="1%" append-to-body :close-on-click-modal="false" :visible.sync="dialogVisible" v-if="dialogVisible" :before-close="handleClose">
      <div>
        <el-form label-width="120px" :model="form" :rules="rules" ref="form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名:" prop="name">
                <el-input v-model.trim="form.name" size="small" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系方式:" prop="mobile">
                <el-input v-model.trim="form.mobile" :disabled="dialogType == 'edit'" size="small" placeholder="请输入姓名" @blur="mobileBlur"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="selectMer.rpiKind === 1">
              <el-form-item label="所属商户:" prop="rpiNo">
                <!-- <el-select size="small" v-model="form.rpiNo" placeholder="请选择所属商户" @change="selectRpiNoConfirm">
                  <el-option v-for="item in rpiNoColumns" :key="item.rpiNo" :label="item.rpiName" :value="item.rpiNo">
                    <span style="float: left">{{ item.rpiName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.rpiNo }}</span>
                  </el-option>
                </el-select> -->

                <select-page
                  ref="searchRpiSelect"
                  label="rpiName"
                  value="rpiNo"
                  :select.sync="form.rpiNo"
                  :url="website.searchLink.merchantUrl"
                  placeholder-text="所属商户"
                  filter-key="searchParam"
                  :params="{rpiGroup:selectMer.rpiNo}"
                  @update:select="selectRpiNoConfirm"
                ></select-page>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="staffType !== 2 && (selectMer.userMerchantType !== 3 && selectMer.userMerchantType !== 4)">
              <el-form-item label="所属门店:" prop="rpsNo">
                <el-select size="small" v-model="form.rpsNo" placeholder="请选择所属门店" @click="openStore" @change="changeStore">
                  <el-option v-for="item in storeColumns" :key="item.rpsNo" :label="item.rpsName" :value="item.rpsNo">
                    <span style="float: left">{{ item.rpsName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.rpsNo }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="isShowPwd && dialogType == 'add'">
              <el-form-item label="密码:" prop="password">
                <el-input v-model.trim="form.password" size="small" placeholder="请输入密码" show-password></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="isShowPwd && dialogType == 'add'">
              <el-form-item label="确认密码:" prop="checkPass">
                <el-input type="show-password" v-model.trim="form.checkPass" size="small" placeholder="请确认密码" show-password></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="退款权限:" prop="isRefundBtn">
                <el-switch :active-value="1" :inactive-value="0" v-model="form.isRefundBtn" />
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="dialogType == 'edit'">
              <el-form-item label="状态:" prop="isOn">
                <el-switch :active-value="1" :inactive-value="0" v-model="form.isOn" />
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => { dialogVisible = false; initForm() }">取 消</el-button>
        <el-button type="primary" @click="submit" :disabled="btnDisable">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 收银员无权限 -->
    <div class="qxWrap" v-if="this.selectMer.userMerchantType === 4">
      <div class="qxH1">暂无权限</div>
    </div>
  </basic-container>
</template>

<script>
import { submitManage, storeList, isStaffPassWord, getList } from "@/api/rb-merchant/posStaff/manage";
import { mapGetters } from "vuex";
import selectPage from "@/components/select-page/select-page";

/**
 * userMerchantType 1.集团商户 2.商户 3.门店 4.收银员
 * showUserType 1.集团商户 2.商户 3.门店 4.收银员 5.商户管理员 6.门店管理员
 */
export default {
  components: {
    selectPage
  },
  data() {
    return {
      rpiNoColumns: [],
      isShowPwd: true,
      staffType: null,
      storeColumns: [],//所属门店
      form: {
        // name: '',
        // mobile: '',
        // password: '',
        // checkPass:'',
        // rpiNo: '',
        // rpsNo: ''//所属门店
      },
      rules: {
        name: {
          type: 'string',
          required: true,
          message: '请输入姓名',
          trigger: ['blur', 'change']
        },
        mobile: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: ['change', 'blur']
          },
          {
            pattern: /^1[0-9]{10}$/,
            message: "手机号格式不正确",
            trigger: ['blur', 'change']
          }
        ],
        password: [
          {
            required: true,
            message: '请输入新密码',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^[a-zA-Z0-9]{6,15}$/,
            message: "密码6-15位，由英文、数字组成",
            trigger: ['blur', 'change']
          }
        ],
        checkPass: [
          {
            required: true,
            message: '请再次输入新密码',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^[a-zA-Z0-9]{6,15}$/,
            message: "密码6-15位，由英文、数字组成",
            trigger: ['blur', 'change']
          }
        ],
        rpiNo: {
          required: true,
          message: '请选择所属商户',
          trigger: ['blur', 'change']
        },
        rpsNo: {
          required: true,
          message: '请选择所属门店',
          trigger: ['blur']
        }
      },

      btnDisable: false,
      dialogVisible: false,
      dialogTitle: '',
      dialogType: '',
      query: {},
      data: [],
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText: '重置',
        column: [
          {
            label: "姓名",
            prop: "rpstName",
            search: true,
            type: "input"
          },
          {
            label: "店员类型",
            prop: "staffType",//number 0 收银员 1 门店管理员 2 商户管理员
            search: true,
            type: "select",
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=staff_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label: "联系方式",
            prop: "rpstPhone",
            search: true,
            type: "input"
          },
          {
            label: "所属商户",
            prop: "rpiName",
            type: "input"
          },
          {
            label: "所属门店",
            prop: "rpsName",
            type: "input"
          },
          {
            label: "状态",
            prop: "isOn",
            type: "input"
          },
          {
            label: "退款权限",
            prop: "isRefundBtn",
            type: "input"
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['selectMer']),
    setIsOnName() {
      return (val) => {
        if (val === 0) {
          return '禁用';
        } else if (val === 1) {
          return '启用';
        } else {
          return ''
        }
      };
    }
  },
  mounted() { },
  created() {
    if (this.selectMer.userMerchantType === 1) {
      this.query.rpiGroup = this.selectMer.rpiNo;
    } else {
      this.query.rpiNo = this.selectMer.rpiNo;
    }
  },
  methods: {
    changeStore(e) {
      this.$refs.form.validateField('rpsNo')
      this.$forceUpdate();
    },
    /* 所属门店 打开回调*/
    openStore() {
      if (!this.form.rpiNo) {
        this.$message.error("请先选择所属商户！");
        this.storeColumns = [];
      }
    },
    /* 所属商户 确定*/
    selectRpiNoConfirm(e) {
      this.form.rpiNo = e;
      this.storeColumns = [];
      this.form.rpsNo = ''
      this.getStoreList();
    },
    /* 选择商户 */
    // rpiNoList() {
    //   getRpiNOList(-1, -1, { rpiExStatus: '3', rpiGroup: this.selectMer.rpiNo }).then(res => {
    //     this.rpiNoColumns = res.data.data.records;
    //   })
    // },
    initForm() {
      this.form = {};
      this.isShowPwd = true;
      this.staffType = null;
      this.dialogType = '';
      this.dialogTitle = '';
    },
    /* 渠道信息提交 */
    submit() {
      this.$refs.form.validate().then(res => {
        if (this.isShowPwd) {
          if (this.form.password !== this.form.checkPass) {
            this.$message.error("两次密码不一致！");
            return false;
          }
        }

        if (this.selectMer.userMerchantType === 1) {
          this.form.rpiGroup = this.selectMer.rpiNo;
        } else {
          if (!this.form.rpiNo) {
            this.form.rpiNo = this.selectMer.rpiNo;
          }
        }

        if (this.selectMer.userMerchantType === 3) {
          if (!this.form.rpsNo) {
            this.form.rpsNo = this.selectMer.rpsNo;
          }
        }

        this.btnDisable = true;
        this.form.staffType = this.staffType;
        // * userMerchantType  Number == 1. 集团商户 2.商户 3.门店 4.收银员


        if (this.dialogType === 'add') {
          submitManage(this.form).then(res => {
            this.initForm();

            this.btnDisable = false;
            this.dialogVisible = false;
            this.$message.success("操作成功!");
            this.refreshChange();
          }, error => {
            this.btnDisable = false;
          });
        } else {
          submitManage(this.form).then(res => {
            this.initForm();

            this.btnDisable = false;
            this.dialogVisible = false;
            this.$message.success("修改成功!");
            this.refreshChange();
          }, error => {
            this.btnDisable = false;
          });
        }
      })
        .catch(errors => {
          this.btnDisable = false;
          this.$message.error("请检查上面内容");
        });
    },
    /* 输入手机号判断是否输入密码 */
    mobileBlur() {
      if (this.form.mobile) {
        isStaffPassWord(this.form.mobile).then(res => {
          this.isShowPwd = res.data.data;
          if (this.isShowPwd == false) {
            this.form.password == '';
            this.form.checkPass == '';
          }
        })
      }
    },
    /* 所属门店 */
    getStoreList() {
      let param = {}
      if (this.dialogType == 'add') {
        if (this.selectMer.userMerchantType === 1) {
          param.rpiNo = this.form.rpiNo;
        } else {
          param.rpiNo = this.selectMer.rpiNo;
        }
      } else {
        param.rpiNo = this.form.rpiNo;
      }
      storeList(param).then(res => {
        this.storeColumns = res.data.data
      })
    },
    handleClose(done) {
      this.initForm();
      done()
    },
    // 新增
    handleAdd(type) {
      this.dialogType = 'add';
      this.staffType = type;

      // if (this.selectMer.userMerchantType === 1) {
      //   this.rpiNoList();
      // }

      // * userMerchantType  Number == 1. 集团商户 2.商户 3.门店 4.收银员
      switch (type) {
        case 0:
          this.dialogTitle = '新建收银员';
          if (this.selectMer.userMerchantType === 2) {
            this.getStoreList();
          }
          break
        case 1:
          this.dialogTitle = '新建门店管理';

          if (this.selectMer.userMerchantType === 2) {
            this.getStoreList();
          }
          break
        case 2:
          this.dialogTitle = '新建商户管理员';
          break
      }
      this.dialogVisible = true;
    },
    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit';
      this.staffType = row.staffType;
      this.form = {
        id: row.id,
        name: row.rpstName,
        mobile: row.rpstPhone,
        password: '',
        checkPass: '',
        rpiNo: row.rpiNo,
        rpsNo: row.rpsNo,//所属门店
        rpsName: row.rpsName,
        staffType: row.staffType,
        isOn: row.isOn,
        isRefundBtn: row.isRefundBtn
      }

      // if (this.selectMer.rpiKind === 1) {
      //   this.rpiNoList();
      // }
      this.getStoreList();

      switch (row.staffType) {
        case 0:
          this.dialogTitle = '编辑收银员';
          break
        case 1:
          this.dialogTitle = '编辑门店管理';
          break
        case 2:
          this.dialogTitle = '编辑商户管理员';
          break
      }

      this.dialogVisible = true;
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      // if (this.selectMer.rpiKind === 1) {
      //   params.rpiGroup = this.selectMer.rpiNo;
      // } else {
      //   params.rpiNo = this.selectMer.rpiNo;

      //   if (this.selectMer.userMerchantType === 3) {
      //     params.rpsNo = this.selectMer.rpsNo
      //   }
      // }
      params.rpiNo = this.selectMer.rpiNo;
      params.rpsNo = this.selectMer.rpsNo;
      // params.rpstNo = this.selectMer.rpstNo;
      params.userMerchantType = this.selectMer.userMerchantType;


      // * userMerchantType 1. 集团商户 2.商户 3.门店 4.收银员
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, {});
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
.qxWrap {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  width: 100%;

  .qxH1 {
    font-size: 22px;
  }
}

/deep/ .el-select--small{
  width: 100% !important;
}
</style>